package com.vivo.Utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.vivo.dingtalk.web.vm.LinkMsgVM;
import com.vivo.dingtalk.web.vm.WorkRecordVM;

import java.util.*;


public class SendDingDingMsgUtil {
    private static String APPKEY = "xxx";

    private static String APPSECRET = "xxx";

    private static Long AGENT_ID = 123L;

    private static Map<String, String> map = new HashMap<>(16);

    public static void main(String[] args) throws Exception {
        send("147****9309", "哈喽...");
    }


    /**
     * 根据手机号码发送工作消息
     * @param mobile
     * @param content
     */
    public static void send(String mobile, String content) {
        try {
            String accessToken = getAccessToken();
            if (map == null) {
                initUserList(accessToken);
            }
            int userListCount = getUserListCount(accessToken);
            if (userListCount > map.size()) {
                initUserList(accessToken);
            }
            senWorkMsg(accessToken, map.get(mobile), content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取 accessToken
     *
     * @return
     * @throws Exception
     */
    private static String getAccessToken() throws Exception {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();

        request.setAppkey(APPKEY);
        request.setAppsecret(APPSECRET);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        String accessToken = response.getAccessToken();
        return accessToken;
    }


    /**
     * 发送工作消息
     *
     * @param accessToken
     * @param userId
     * @param content
     * @throws Exception
     */
    private static void senWorkMsg(String accessToken, String userId, String content) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(userId);
        request.setAgentId(AGENT_ID);
        request.setToAllUser(false);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("head");
        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
        msg.getOa().getBody().setContent(content);
        msg.setMsgtype("oa");
        request.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, accessToken);

    }

    /**
     * 部门用户列表
     *
     * @param accessToken
     * @throws Exception
     */
    private static void initUserList(String accessToken) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        request.setDepartmentId(1L);
        request.setOffset(0L);
        request.setSize(10L);
        request.setHttpMethod("GET");

        OapiUserSimplelistResponse response = client.execute(request, accessToken);
        List<OapiUserSimplelistResponse.Userlist> userlist = response.getUserlist();
        for (OapiUserSimplelistResponse.Userlist user : userlist) {
            String userId = user.getUserid();
            String mobile = getMobile(accessToken, userId);
            map.put(mobile, userId);
        }
    }

    /**
     * 获取部门用户数量
     *
     * @param accessToken
     * @return
     * @throws Exception
     */
    private static int getUserListCount(String accessToken) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        request.setDepartmentId(1L);
        request.setOffset(0L);
        request.setSize(10L);
        request.setHttpMethod("GET");

        OapiUserSimplelistResponse response = client.execute(request, accessToken);
        List<OapiUserSimplelistResponse.Userlist> userlist = response.getUserlist();
        return userlist.size();
    }


    /**
     * 根据部门ID递归获取所有用户信息
     * @param accessToken
     * @param deptId
     * @return
     */
    public static List<OapiUserListResponse.Userlist> getUserDetailList(String accessToken, Long deptId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/list");
        OapiUserListRequest request = new OapiUserListRequest();
        Long pageSize = 20L;
        request.setDepartmentId(deptId);
        request.setHttpMethod("GET");
        request.setSize(pageSize);
        Long offset = 0L;
        boolean hasMore = true;
        List<OapiUserListResponse.Userlist> userList = new ArrayList<>();

        while (hasMore) {
            request.setOffset(offset);

            try {
                OapiUserListResponse response = client.execute(request, accessToken);
                hasMore = response.getHasMore();
                userList.addAll(response.getUserlist());
            } catch (Exception e) {
                hasMore = false;
                e.printStackTrace();
            }

            offset += pageSize;
        }

        return userList;
    }


    /**
     * 获取所有部门列表
     * @param accessToken
     * @return
     * @throws Exception
     */
    public static List<OapiDepartmentListResponse.Department> getAllDeptList(String accessToken, String id){
        if (StringUtils.isBlank(id)) {
            id = "1";
        }
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId(id);
        request.setFetchChild(true);
        request.setHttpMethod("GET");
        List<OapiDepartmentListResponse.Department> departmentList = null;
        try {
            OapiDepartmentListResponse response = client.execute(request, accessToken);
            departmentList = response.getDepartment();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return departmentList;
    }


    /**
     * 根据 userId 获取手机号
     *
     * @param accessToken
     * @param userId
     * @return
     * @throws Exception
     */
    private static String getMobile(String accessToken, String userId) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userId);
        request.setHttpMethod("GET");
        OapiUserGetResponse response = client.execute(request, accessToken);
        return response.getMobile();
    }


    public static OapiWorkrecordAddResponse sendWorkRecord(WorkRecordVM workRecordVM) throws Exception {
        Date nowDate = new Date();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/add");
        OapiWorkrecordAddRequest req = new OapiWorkrecordAddRequest();
        req.setUserid(workRecordVM.getDingUserId());
        req.setCreateTime(nowDate.getTime());
        req.setTitle(workRecordVM.getTitle());
        req.setUrl(workRecordVM.getUrl());
        List<OapiWorkrecordAddRequest.FormItemVo> list2 = new ArrayList<OapiWorkrecordAddRequest.FormItemVo>();
        OapiWorkrecordAddRequest.FormItemVo obj3 = new OapiWorkrecordAddRequest.FormItemVo();
        list2.add(obj3);
        obj3.setTitle(workRecordVM.getFormTitle());
        obj3.setContent(workRecordVM.getFormCont());
        req.setFormItemList(list2);
        OapiWorkrecordAddResponse rsp = client.execute(req, workRecordVM.getAccessToken());

        System.out.println(rsp.getBody());
        return rsp;
    }

    public static OapiWorkrecordUpdateResponse updWorkRecord(String access_token, String userId, String recordId) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/update");
        OapiWorkrecordUpdateRequest req = new OapiWorkrecordUpdateRequest();
        req.setUserid(userId);
        req.setRecordId(recordId);
        OapiWorkrecordUpdateResponse rsp = client.execute(req, access_token);
        System.out.println(rsp.getBody());
        return rsp;
    }

    public static OapiMessageCorpconversationAsyncsendV2Response sendWorkMsg(LinkMsgVM linkMsg) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(linkMsg.getDingUserId());
        request.setAgentId(linkMsg.getAgentId());
        request.setToAllUser(false);
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText(linkMsg.getTitle());
        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
//        msg.getOa().getBody().setContent(linkMsg.getContent());
        msg.getOa().getBody().setTitle(linkMsg.getContent());
        if (linkMsg.getBodyContent() != null && linkMsg.getBodyContent().length() > 1) {
            msg.getOa().getBody().setContent(linkMsg.getBodyContent());
        }
        msg.getOa().setMessageUrl(linkMsg.getUrl());
        msg.setMsgtype("oa");
        request.setMsg(msg);

        OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request, linkMsg.getAccessToken());

        return response;
    }
}
